package com.ttxs.uaa.api.common;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ttxs.common.core.vo.R;
import com.ttxs.uaa.api.BaseApi;
import com.ttxs.common.core.constant.Api;
import com.ttxs.common.core.constant.Common;
import com.ttxs.uaa.entity.SysMenu;
import com.ttxs.uaa.service.ISysMenuService;
import com.ttxs.uaa.vo.MenuParamVO;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author 天天向上
 * @since 2021-07-26
 */
@RestController
@RequestMapping(Api.Common.Menu.PREFIX)
@RequiredArgsConstructor
public class MenuApi extends BaseApi {
    private final ISysMenuService sysMenuService;
    private static final String COMMON_API_URL_PREFIX = "/" + Common.Global.ADMIN_PLATFORM_NAME + Api.COMMON_PREFIX;
    /*@PostMapping(Api.Common.Menu.ROLE_MENUS)
    public AjaxResult roleMenus(@RequestBody MenuParamVO menuParamVO) {
        return AjaxResult.ok(sysMenuService.getMenus(menuParamVO.getPlatformId(), menuParamVO.getRoleNames()));
    }*/

    /**
     * 根据角色名字查询对应的权限菜单，用于前端菜单显示
     * @param menuParamVO
     * @return
     */
    @PostMapping(Api.Common.Menu.USER_MENUS)
    public R userMenus(@RequestBody @Validated MenuParamVO menuParamVO) {
        return R.ok(sysMenuService.getMenuTree(menuParamVO.getPlatformId(), menuParamVO.getRoleNames()));
    }


    @GetMapping
    public R list(@RequestParam("page") int pageNo,
                  @RequestParam("limit") int pageSize) {
        Page<SysMenu> page = sysMenuService.page(Page.of(pageNo, pageSize),
                new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getPlatformId, getPlatformId()));
        return R.ok(page);
    }

    @GetMapping(Api.Common.Menu.LIST_ALL)
    public R listAll() {
        List<SysMenu> list = sysMenuService.list(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getPlatformId, getPlatformId())
                .orderByAsc(SysMenu::getParentId, SysMenu::getOrderNum));
        return R.ok(list);
    }

    @PostMapping
    public R add(@RequestBody SysMenu sysMenu) {
        // 添加平台名字到api路径，以便后续鉴权
        /*if(!sysMenu.isSpringCloud() && StringUtils.hasText(sysMenu.getApiUrl())) {
            sysMenu.setApiUrl("/" + getPlatformName() + sysMenu.getApiUrl());
        }*/
        sysMenu.setPlatformId(getPlatformId());
        // 不能以/ttxs/common开头
        if(StringUtils.hasText(sysMenu.getApiUrl())) {
            if(sysMenu.getApiUrl().startsWith(COMMON_API_URL_PREFIX)) {
                return R.error("后端api接口不能以【" + COMMON_API_URL_PREFIX + "】开头");
            }
        }
        // 检查api路径是否存在
        long count = 0;
        if(StringUtils.hasText(sysMenu.getApiUrl())) {
            count = sysMenuService.count(new LambdaQueryWrapper<SysMenu>()
                    .eq(SysMenu::getApiUrl, sysMenu.getApiUrl())
                    .eq(SysMenu::getPlatformId, sysMenu.getPlatformId()));
            if (count > 0) {
                return R.error("后端api接口已经存在");
            }
        }
        // 检查前端组件路径是否存在
        if (StringUtils.hasText(sysMenu.getComponent())) {
            count = sysMenuService.count(new LambdaQueryWrapper<SysMenu>()
                            /*.eq(SysMenu::getPlatformId, sysMenu.getPlatformId())*/
                            .eq(SysMenu::getComponent, sysMenu.getComponent())
                    );
            if (count > 0) {
                return R.error("前端组件地址已经存在");
            }
        }
        sysMenuService.save(sysMenu);
        return R.ok(sysMenu);
    }

    @GetMapping("/{id}")
    public R get(@PathVariable Long id) {
        return R.ok(sysMenuService.getById(id));
    }

    @GetMapping(Api.Common.Menu.SEARCH)
    public R teamSearch(SysMenu sysMenu) {
        return R.ok(sysMenuService.list(new QueryWrapper<>(sysMenu)));
    }

    @DeleteMapping("/{id}")
    public R del(@PathVariable Long[] id) {
        long count = sysMenuService.count(new LambdaQueryWrapper<SysMenu>().in(SysMenu::getParentId, id));
        if(count >0) {
            return R.error("请先删除【" + count + "】个子菜单");
        }
        return R.ok(sysMenuService.removeByIds(Arrays.asList(id)));
    }

    @PutMapping("/{id}")
    public R update(@PathVariable Long id, @RequestBody SysMenu sysMenu) {
        sysMenu.setMenuId(id);
        return R.ok(sysMenuService.saveOrUpdate(sysMenu));
    }
}
